package com.example.multithread.communication;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @ClassName SemaphoreDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/5/14 11:30 AM
 * @Version 1.0
 */
public class SemaphoreDemo {

	private final static Logger log = LoggerFactory.getLogger(SemaphoreDemo.class);
	public static void main(String[] args) throws InterruptedException {
		Semaphore semaphore = new Semaphore(2, true);
		CountDownLatch countDownLatch = new CountDownLatch(10);
		ExecutorService executorService = Executors.newFixedThreadPool(20);
		IntStream.rangeClosed(1,20).forEach((i)-> executorService.execute(() -> {
			try {
				semaphore.acquire();
				countDownLatch.countDown();
				Thread.sleep(100);
				log.info("当前线程是{}, 还有{}个信号, 还有{}个线程在等待中.", Thread.currentThread().getName(), semaphore.availablePermits(), semaphore.getQueueLength());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				semaphore.release();
			}

		}));
		countDownLatch.await();
	}
}
